package multiplayer.lan;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Observable;

public class ServersOnAir extends Observable{
	public static long TIME_OUT=3500;
	
	private volatile HashMap<String, ServerInfo> servers = new HashMap<String, ServerInfo>(); 
	private volatile HashMap<String, Long> timeOut = new HashMap<String, Long>();
	
	
	public void addServer(String ip ,String nome , int port){
		if(!servers.containsKey(ip)){
			servers.put(ip, new ServerInfo(nome, ip, port));
			timeOut.put(ip, System.currentTimeMillis());
		}else{
			timeOut.remove(ip);
			timeOut.put(ip, System.currentTimeMillis());
			setChanged();
			notifyObservers(this);
		}
	}
	public void clearServers(){
		Iterator<String> ip=timeOut.keySet().iterator();
		while(ip.hasNext()){
			String currentIp=ip.next();
			if((System.currentTimeMillis()-timeOut.get(currentIp))>TIME_OUT){
				ip.remove();
				servers.remove(currentIp);
				setChanged();
				notifyObservers(currentIp);
			}
		}
	}
	public void print(){
		Iterator<String> ip=servers.keySet().iterator();
		while(ip.hasNext()){
			String currentIp=ip.next();
			System.out.println(currentIp +" "+ servers.get(currentIp));
		}
	}
	public HashMap<String, ServerInfo> getServers(){
		return servers;
	}
}
